<template>
  <div>
    <div class="container">
      <div style="min-height: 50px;text-align: center;">
         <el-radio-group @change="radioChange" v-model="reportClassId">
            <el-radio-button :label="key" v-for="(value,key,index) in dict_reportClass" :key="key">{{value}}</el-radio-button>
          </el-radio-group>
      </div>
      <vxe-input style="float: right;margin-top: 10px;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
        @input="searchEvent"></vxe-input>
      <h3>已保存了的报表</h3>
      <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row
        :loading="loading" :data="dataList" @sort-change="sortChange">
        <vxe-table-column field="name" title="报表名" sortable></vxe-table-column>
        <vxe-table-column field="reportClass" title="报表类型" sortable></vxe-table-column>
        <vxe-table-column field="" title="操作" width="110">
          <template #default="{ row }">
            <el-tooltip class="item" effect="dark" content="查看报表" placement="top-start">
              <el-button @click="prevewReport(row)" type="primary" circle size="medium" icon="el-icon-view"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="打印报表" placement="top-end">
              <el-button @click="printReport(row)" type="primary" circle size="medium" icon="el-icon-printer"></el-button>
            </el-tooltip>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
    <!-- 查看 -->
    <vxe-modal v-model="previewModal" title="报表查看" height="800" show-zoom resize width="1000" show-footer>
      <template #default>
        <bfViewTablePreview v-if="reportClassId==13&&Object.keys(previewData).length!=0" :previewData="previewData" :dict_meta="dict_meta" />
        <tendencyReportPreview v-else-if="reportClassId==14&&Object.keys(previewData).length!=0" :previewData="previewData" :dict_meta="dict_meta" />
        <contrastReportPreview v-else :previewData="previewData" :dict_meta="dict_meta" />
        <p>报表名称(保存报表需要先给该报表起个名字)</p>
        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model="reportName"></el-input>
        <p>评价</p>
        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model="reportMemo"></el-input>
      </template>
      <template #footer>
        <el-button @click="saveEvent" type="primary" icon="el-icon-s-promotion" size="mini">保存</el-button>
      </template>
    </vxe-modal>
    <!-- 打印 -->
    <vxe-modal v-model="printModal" title="打印预览" height="800" show-zoom resize width="1000" show-footer>
      <template #default>
        <bfViewTablePreview v-if="reportClassId==13&&Object.keys(printData).length!=0"x id="myPrint" :previewData="printData" :dict_meta="dict_meta" />
        <tendencyReportPreview v-else-if="reportClassId==14&&Object.keys(printData).length!=0" ref="myPrint" id="myPrint" :previewData="printData" :dict_meta="dict_meta" />
        <contrastReportPreview v-else id="myPrint" :previewData="printData" :dict_meta="dict_meta" />
      </template>
      <template #footer>
        <el-button @click="printEvent" type="primary" icon="el-icon-printer" size="mini">打印</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
  import {
    sport_by_org,
    coach_by_org,
    currentRolePlayer,
    pcm4player,
    coach_by_sport
  } from '@/api/dict.js'
  import {analysisReport,personContrastReport,updateReportMemo,bf_meta_all} from '@/api/meta.js'
  import bfViewTablePreview from '@/components/bfViewTable/bfViewTablePreview.vue'
  import tendencyReportPreview from '@/components/bfViewTable/personTendencyReportPreview.vue'
  import contrastReportPreview from '@/components/bfViewTable/personContrastReportPreview.vue'
  export default {
    components: {
      bfViewTablePreview,
      tendencyReportPreview,
      contrastReportPreview
    },
    data() {
      return {
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        searchProps: [],
        dict_coach: {},
        dict_player: {},
        dict_sport: {},
        dict_meta: {},
        searchForm: {
          sportId: '',
          coachId: '',
          playerId: [],
          packageId: [],
        },
        dict_sport: {},
        dict_coach: {},
        coachData: {},
        dict_player: {},
        playerData: {},
        previewModal: false,
        printModal: false,
        previewData: {},
        printData: {},
        reportName: '',
        reportMemo: '',
        reportClassId: 13,
        dict_reportClass: {
          13: '体能测评个人报表',
          14: '体能测评趋势报表',
          15: '体能测评对比报表'
        },
        search: false,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.analysisReport()
      })
    },
    watch: {
      previewModal(val) {
        if(!val) {
          this.previewData = {}
        }
      },
      printModal(val) {
        if(!val) {
          this.printData = {}
          document.title = this.$route.meta.title
        }
      },
      filterName(val) {
        if(!val){
          this.page = {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0,
          }
          this.search = false
          this.findList()
        }
      }
    },
    methods: {
      radioChange(val) {
        this.page = {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        this.analysisReport()
      },
      saveEvent() {
        let data = {
          reportDataId: this.reportDataId,
          name: this.reportName,
          memo: this.reportMemo
        }
        updateReportMemo(data).then(res=>{
          if(res.code === 200) {
            this.$message.success('保存成功！')
            this.analysisReport()
          }else{
            this.$message.error(res.message)
          }
        })
      },
      printEvent() {
        if(this.$refs.myPrint){
          this.$refs.myPrint.print()
        }
        document.title = this.dict_reportClass[this.reportClassId]
        setTimeout(()=>{
          const divEl = document.getElementById('myPrint')
          this.$XPrint({
            sheetName: this.dict_reportClass[this.reportClassId],
            content: divEl.innerHTML
          })
        },200)
      },
      prevewReport(row){
        let jsonData = JSON.parse(row.jsonData)
        this.previewData = jsonData
        this.reportDataId = row.reportDataId
        this.reportName = row.name
        this.reportMemo = row.memo
        this.previewModal = true
      },
      printReport(row){
        let jsonData = JSON.parse(row.jsonData)
        this.printData = jsonData
        this.printModal = true
      },
      exportDataAll() {
        this.$refs.XTable.exportData({
          filename: '体能测评个人报表',
          data: this.search?this.dataList:this.defaultDataList
        })
      },
      printEventAll() {
        let topHtml = '<h2>体能测评个人报表</h2>'
        this.searchEvent()
        setTimeout(() => {
          this.$refs.XTable.print({
            sheetName: '体能测评个人报表',
            beforePrintMethod: ({
              content
            }) => {
              return topHtml + content
            }
          })
        }, 1000)
      },
      searchClear() {
        this.searchForm = {
          sportId: '',
          coachId: '',
          playerId: [],
          packageId: []
        }
        this.analysisReport()
      },
      analysisReport() {
        let data = {
          reportClassId: this.reportClassId
        }
        this.loading = true
        analysisReport(data).then(res=>{
          if(res.code === 200) {
            if(res.data.length!=0){
              res.data.forEach(item=>{
                item.reportClass = this.dict_reportClass[item.reportClassId]
              })
              this.page = {
                currentPage: 1,
                pageSize: 10,
                totalResult: 0
              }
              this.search = true
              this.defaultDataList = res.data
              this.searchProps = Object.keys(res.data[0])
            }else{
              this.defaultDataList = []
            }
          }else{
            this.defaultDataList = []
            this.$message.error(res.message)
          }
        }).then(()=>{
          this.loading = false
          this.findList()
        })
      },
      sportChange (val) {
        this.searchForm.coachId = ''
        this.searchForm.playerId = ''
        this.coachData = {}
        this.playerData = {}
        let sportId = this.searchForm.sportId || val
        if(sportId){
          coach_by_sport({sportId:sportId}).then(res=>{
            this.coachData = res
          })
          pcm4player({sportId:sportId}).then(res=>{
            this.playerData = res
          })
        }
      },
      coachChange (val) {
        this.searchForm.playerId = ''
        this.playerData = {}
        let coachId = this.searchForm.coachId || val
        let data = {}
        if(this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if(this.searchForm.coachId) data.coachId = this.searchForm.coachId
        if(coachId){
          pcm4player(data).then(res=>{
            this.playerData = res
          })
        }
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          bf_meta_all().then(res=>{
            let dict = {}
            res.data.forEach(item=>{
              dict[item.metaId] = item.name
            })
            this.dict_meta = dict
          })
          currentRolePlayer().then(res=>{
            this.dict_player = res
            this.playerData = res
            resolve()
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
            currentPage: 1,
            pageSize: this.dataList.length,
            totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
     }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
        if(!this.search){
          this.page.pageSize = this.defaultDataList.length
          this.findList()
        }else{
          this.page.pageSize = this.dataList.length
        }
      },
      findList() {
        setTimeout(() => {
          this.loading = false
          this.page.totalResult = this.defaultDataList.length
          this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
            .pageSize, this.page.currentPage * this.page.pageSize)
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
.container {
    padding: 10px;
    background-color: #FFFFFF;
  }
</style>
